import { useAxios } from '../hooks/useAxios'

/**
 * 防抖函数
 * @param {Function} fn
 * @param {Number} duration
 * @returns {Function}
 */
export function debounce(fn, duration = 300) {
  let timeout
  return function (...args) {
    const later = () => {
      clearTimeout(timeout)
      fn(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, duration)
  }
}

export async function getFilesize(url) {
  console.log('%c Line:22 🥖 url', 'color:#fca650', url)
  const { http } = useAxios()
  const response = await http.get(url, { responseType: 'blob' })
  console.log('%c Line:24 🍊 response', 'color:#4fff4B', response)
}

export function formatByte(bytes, decimals = 2) {
  if (bytes === 0) return '0 B'

  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']

  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

/**
 * 把扁平数组转成树结构
 * @param {Array} arr 原始扁平数据
 * @param {Object} option  配置项
 *   @param {String|Number} option.rootPid  根节点 pid 的值，默认 0
 *   @param {String} option.idKey     主键字段，默认 'id'
 *   @param {String} option.pidKey    父节点字段，默认 'pid'
 *   @param {String} option.childKey  放子节点的字段，默认 'children'
 *   @param {Boolean} option.sort     是否按 orderby 升序，默认 false
 * @returns {Array} 树结构数组
 */
export function tree(arr, option = {}) {
  const { rootPid = 0, idKey = 'id', pidKey = 'pid', childKey = 'children', sort = false } = option

  // 节点映射表  id -> 节点
  const nodeMap = new Map()
  // 根节点数组
  const roots = []

  // 第一次循环：把每个节点先放进 map，同时挂到父节点的 children 里
  arr.forEach((item) => {
    const id = item[idKey]
    const pid = item[pidKey]

    // 如果当前节点已经存在于 map 中（之前作为别人的父节点被占位了），直接复用
    let node = nodeMap.get(id)
    if (!node) {
      node = { ...item, [childKey]: [] }
      nodeMap.set(id, node)
    } else {
      // 占位时只有 children，把其它字段补上
      Object.assign(node, item)
    }

    // 根节点
    if (pid == rootPid) {
      roots.push(node)
    } else {
      // 找父节点
      let parent = nodeMap.get(pid)
      if (!parent) {
        // 父节点还没出现，先占位
        parent = { [idKey]: pid, [childKey]: [] }
        nodeMap.set(pid, parent)
      }
      parent[childKey].push(node)
    }
  })

  // 如果需要排序，递归给每层排一下
  if (sort) {
    const walk = (arr) => {
      arr.sort((a, b) => (a.orderby || 0) - (b.orderby || 0))
      arr.forEach((n) => n[childKey] && walk(n[childKey]))
    }
    walk(roots)
  }

  return roots
}
